package pl.edu.mimuw.irs.core.model.design.resource;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.LinkedHashMap;
import java.util.Map;

public class Roles extends LinkedHashMap<String, Role> implements IHolder<Role> {

	private static final long serialVersionUID = -4093127548829396332L;
	
	// *** Properties
	public static final String ROLE = "ROLE";
	
	// *** Attributes

	private transient PropertyChangeSupport listeners;
	public PropertyChangeSupport getListeners() {
		if (listeners == null) listeners = new PropertyChangeSupport(this);
		return listeners;
	}
	
	// *** Methods
	
	@Override
	public Role put(String key, Role value) {
		if (!this.containsKey(key)) {
			Role role = super.put(key, value);
			getListeners().firePropertyChange(ROLE, null, value);
			return role;
		} else {
			return super.put(key, value);
		}
	}
	
	@Override
	@Deprecated
	public void putAll(Map<? extends String, ? extends Role> m) {
		throw new UnsupportedOperationException();
	}
	
	@Override
	public Role remove(Object key) {
		Role role = super.remove(key);
		getListeners().firePropertyChange(ROLE, role, null);
		return role;
	}
	
	public boolean add(Role role) {
		if (role != null) {
			put(role.getName(), role);
			role.setRoles(this);
			return true;
		}
		return false;
	}
	
	public boolean remove(Role role) {
		remove(role.getName());
		if (role.getRoles() == this) role.setRoles(null);
		return true;
	}
	
	public void addPropertyChangeListener(PropertyChangeListener listener) {
		getListeners().addPropertyChangeListener(listener);
	}
	
	public void removePropertyChangeListener(PropertyChangeListener listener) {
		getListeners().removePropertyChangeListener(listener);
	}
}
